package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Installation;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegistNickName extends Activity {
	static final String emailOfSender = "d.chaow@gmail.com";
	private EditText editText1;
	private EditText password1, password2;
	private Button btnConfirm;
	private String flag = "";
	ProgressDialog dialog;
	private LocalBroadcastManager localBroadMgr;
	private String registration = "";
	private String email, password;
	

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.v("d", result);
			if(result.equalsIgnoreCase("success")){
				Preferences.setBoolean(getBaseContext(), "isRegisted", true);
				Preferences.setBoolean(getBaseContext(), "configNewStory", true);
				Preferences.setBoolean(getBaseContext(), "configNewChat", true);
				dialog.dismiss();
				finish();
			}
			else{
				dialog.dismiss();
				finish();
			}
		}
	}

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Message msg = new Message();
			Bundle bundle = new Bundle();
			bundle.putString("result", result);
			msg.setData(bundle);
			regHandler.sendMessage(msg);
		}
	}


	private class UploadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			flag = "nickname";
		}
	}

	private class CheckEmailTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("success")){
//				changeTag();
				flag = "nickname";
				if(password1.getText().toString().equals(password2.getText().toString()) && password1.length() >= 8 && password1.length() <= 12){
					password = password1.getText().toString();
					Log.v("d","test : " + Preferences.getValue(getBaseContext(), "nick_name"));
					if(!Preferences.getValue(getBaseContext(), "nick_name").equals("null") && !Preferences.getValue(getBaseContext(), "nick_name").equals("")){
				        UploadAsynkTask2 task = new UploadAsynkTask2();
				        String[] params = new String[]{ServerURL.registEmail, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "email", email, "password", password};
				        task.execute(params);
					}
					else{
						password1.setVisibility(View.GONE);
						password2.setVisibility(View.GONE);
						editText1.setVisibility(View.VISIBLE);
						editText1.setText("");
						editText1.setHint("사용하실 닉네임을 입력해 주세요.");
						flag = "nickname";
					}
				}
				else{
					if(!password1.getText().toString().equals(password2.getText().toString())){
						Toast.makeText(getBaseContext(), "비밀번호가 맞지 않습니다.", Toast.LENGTH_SHORT).show();
					}
					else{
						Toast.makeText(getBaseContext(), "비밀번호는 8~12자 이어야 합니다.", Toast.LENGTH_SHORT).show();
					}
				}
			}
			else{
				Toast.makeText(getBaseContext(), "중복된 이메일주소 입니다.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private void changeTag(){
		email = editText1.getText().toString();
		editText1.setVisibility(View.GONE);
		password1.setVisibility(View.VISIBLE);
		password2.setVisibility(View.VISIBLE);
		password1.setHint("비밀번호를 입력해 주세요.");
		password2.setHint("비밀번호를 다시 입력해 주세요.");
		flag = "nickname";
	}

	private BroadcastReceiver registLocalcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if( bundle != null && bundle.containsKey("isReg")){
				if(bundle.getBoolean("isReg")){
					registration = bundle.getString("registration");
					Preferences.setValue(getBaseContext(), "registration", registration);
					
					DownloadAsynkTask task = new DownloadAsynkTask();
					String[] params = {ServerURL.registDeviceToken, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "device_token", registration};
					task.execute(params);
				}
			}
		}
	};
	
	Handler regHandler = new Handler(){
		@SuppressLint({ "HandlerLeak", "HandlerLeak" })
		@Override
		public void handleMessage(Message msg) {
//			finish();
			JSONArray resultJson;
			try {
				resultJson = new JSONArray(msg.getData().getString("result"));
				JSONObject resultObject = resultJson.getJSONObject(0);
				if(resultObject.getString("state").equalsIgnoreCase("success")){
					Preferences.setValue(getBaseContext(), "user_id", resultObject.getString("user_id"));
					Preferences.setValue(getBaseContext(), "favorite_id", resultObject.getString("favorite_id"));
					Preferences.setValue(getBaseContext(), "theme_id", resultObject.getString("theme_id"));
					Preferences.setValue(getBaseContext(), "deny_id", resultObject.getString("deny_id"));
					Preferences.setValue(getBaseContext(), "version", "1.2");
					Preferences.setValue(getBaseContext(), "uuid", Installation.id(getBaseContext()));
					Preferences.setValue(getBaseContext(), "nick_name", editText1.getText().toString());
					
					registC2DM();
				}
				else{
				}
			} catch (JSONException e) {
			}
			dialog.dismiss();
			dialog.setTitle("서버의 응답을 기다리고 있습니다.");
			dialog.show();
		}
	};
	
	private boolean emailForm(String form){
		String[] values = form.split("@");
		if(values.length == 2){
			if(values[1].contains(".")){
				return true;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist_nick_name);
		flag = "email";
		
		editText1 = (EditText) findViewById(R.id.editText1);
		password1 = (EditText) findViewById(R.id.password1);
		password2 = (EditText) findViewById(R.id.password2);
//		password1.setVisibility(View.GONE);
//		password2.setVisibility(View.GONE);
		editText1.setHint("이메일을 입력해 주세요.");
		btnConfirm = (Button) findViewById(R.id.btnConfirm);
		
		btnConfirm.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(flag.equals("email")){
					email = editText1.getText().toString();
					if(emailForm(email)){
						CheckEmailTask task = new CheckEmailTask();
						String[] params = {ServerURL.checkEmail, "email", editText1.getText().toString()};
						task.execute(params);
						flag = "nickname";
					}
					else{
						Toast.makeText(getBaseContext(), "아이디는 이메일형식이어야 합니다.", Toast.LENGTH_SHORT).show();
					}
//				}
//				else if(flag.equals("password")){
//					if(password1.getText().toString().equals(password2.getText().toString()) && password1.length() >= 8 && password1.length() <= 12){
//						password = password1.getText().toString();
//						Log.v("d","test : " + Preferences.getValue(getBaseContext(), "nick_name"));
//						if(!Preferences.getValue(getBaseContext(), "nick_name").equals("null") && !Preferences.getValue(getBaseContext(), "nick_name").equals("")){
//					        UploadAsynkTask2 task = new UploadAsynkTask2();
//					        String[] params = new String[]{ServerURL.registEmail, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "email", email, "password", password};
//					        task.execute(params);
//						}
//						else{
//							password1.setVisibility(View.GONE);
//							password2.setVisibility(View.GONE);
//							editText1.setVisibility(View.VISIBLE);
//							editText1.setHint("사용하실 닉네임을 입력해 주세요.");
//							flag = "nickname";
//						}
//					}
//					else{
//						if(!password1.getText().toString().equals(password2.getText().toString())){
//							Toast.makeText(getBaseContext(), "비밀번호가 맞지 않습니다.", Toast.LENGTH_SHORT).show();
//						}
//						else{
//							Toast.makeText(getBaseContext(), "비밀번호는 8~12자 이어야 합니다.", Toast.LENGTH_SHORT).show();
//						}
//					}
				}
				else if(flag.equals("nickname")){
					if(editText1.getText().toString().length() > 0 && editText1.getText().toString().length() < 8){
						dialog = ProgressDialog.show(RegistNickName.this, null, "서버에 등록 중입니다.");
				        UploadAsynkTask task = new UploadAsynkTask();
				        String[] params = new String[]{ServerURL.registUser, "uuid", Installation.id(getBaseContext()), "device_token", registration,
				        		                       "device_type", "android", "nick_name", editText1.getText().toString(), "email", email, "password", password};
				        task.execute(params);
					}
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		broadcastListner();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		localBroadMgr.unregisterReceiver(registLocalcastReceiver);
	}
	
	private void broadcastListner(){
		localBroadMgr = LocalBroadcastManager.getInstance(getBaseContext());
        IntentFilter filter = new IntentFilter("registration");
        filter.addCategory("regist");
        localBroadMgr.registerReceiver(registLocalcastReceiver, filter);
	}
	
	public void registC2DM(){
    	Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    	registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
    	registrationIntent.putExtra("sender", emailOfSender);
    	startService(registrationIntent);
	}
	    
//    private void unRegistC2DM(){
//    	Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
//    	unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
//    	startService(unregIntent);
//    }
}
